<template>
    <div class="user">
        <el-row>
            <el-col :span="24">
                <el-breadcrumb separator="/">
                    <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
                    <el-breadcrumb-item><a href="/">用户管理</a></el-breadcrumb-item>
                    <el-breadcrumb-item>用户列表</el-breadcrumb-item>
                </el-breadcrumb>
            </el-col>
        </el-row>
        <!----- 搜索区域 ---->
        <el-row>
            <el-col :span="24">
                                               <!-- 给组件绑定原生事件的话，需要一个.native的修饰符 -->
                <el-input placeholder="请输入内容" class="search-input" v-model="query" @keydown.native.enter="initList">
                    <el-button slot="append" icon="el-icon-search" @click="initList"></el-button> 
                </el-input> 
                <el-button type="success" plain  @click="addDialogFormVisible = true">添加用户</el-button>
            </el-col> 
        </el-row>
        <!---- 表格区域 ---->
        <el-table class="margin20" v-loading = "loading" :data="userList" border style="width: 100%">
            <el-table-column type="index"  width="50"></el-table-column>
            <el-table-column prop="username" label="姓名" width="180"></el-table-column>
            <el-table-column prop="email" label="邮箱" width="180"></el-table-column>
            <el-table-column prop="mobile" label="电话"></el-table-column>
            <el-table-column label="用户状态">
                <template slot-scope="scope">
                       <!-- 动态获取用户状态 -->
                    <el-switch v-model="scope.row.mg_state" @change="changeUserState(scope.row)"></el-switch>
                </template>
            </el-table-column>
            <el-table-column label="操作">
                <template slot-scope="scope">
                        <!-- 给编辑按钮添加点击事件 -->
                      <el-button size="mini" type="primary" icon="el-icon-edit" plain @click="showEditDialogFormVisible(scope.row)"></el-button>
                             <!-- 给删除按钮添加点击事件 -->
                      <el-button size="mini" type="danger" icon="el-icon-delete" plain @click="showDeleteDialogFormVisible(scope.row)"></el-button>
                             <!-- 给分配角色按钮添加点击事件 -->
                      <el-button size="mini" type="warning" icon="el-icon-check" plain @click="showgrantDialogFormVisible(scope.row)"></el-button>
                </template>
            </el-table-column>
        </el-table>
        <div class="page">
            <el-pagination
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="1"
                :page-sizes="[10, 20, 30, 40]"
                :page-size="10"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total">
            </el-pagination>
        </div>
            <!-- 点击添加用户的添加用户对话框区域 -->
        <el-dialog title="添加用户" :visible.sync="addDialogFormVisible">
                 <!-- rules属性添加用户表单的校验规则 -->
            <el-form :model="addForm" label-width="80px" :rules="rules" ref="addUserForm">
              <el-form-item label="用户名" prop="username">
                <el-input v-model="addForm.username"></el-input>
              </el-form-item>
              <el-form-item label="密码" prop="password">
                <el-input v-model="addForm.password"></el-input>
              </el-form-item>
              <el-form-item label="邮箱" prop="email">
                <el-input v-model="addForm.email"></el-input>
              </el-form-item>
              <el-form-item label="电话" prop="mobile">
                <el-input v-model="addForm.mobile"></el-input>
              </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
              <el-button @click="addDialogFormVisible = false">取 消</el-button>
              <el-button type="primary" @click="addUserSubmit('addUserForm')">确 定</el-button>
            </div>
        </el-dialog>
        <!-- 点击编辑用户对话框区域 -->
        <el-dialog title="编辑用户" :visible.sync="editDialogFormVisible">
                 <!-- rules属性编辑用户表单的校验规则 -->
            <el-form :model="editForm" label-width="80px" :rules="rules" ref="editUserForm">
              <el-form-item label="用户名" prop="username">
                <el-input v-model="editForm.username" :disabled="true"></el-input>
              </el-form-item>
              <el-form-item label="邮箱" prop="email">
                <el-input v-model="editForm.email"></el-input>
              </el-form-item>
              <el-form-item label="电话" prop="mobile">
                <el-input v-model="editForm.mobile"></el-input>
              </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
              <el-button @click="editDialogFormVisible = false">取 消</el-button>
              <el-button type="primary" @click="editUserSubmit('editUserForm')">确 定</el-button>
            </div>
        </el-dialog>
           <!-- 点击获取角色列表对话框 -->
        <el-dialog title="分配角色" :visible.sync="grantDialogFormVisible">
            <el-form :model="grantForm" label-width="120px">
              <el-form-item label="当前的用户:" prop="username">
                <el-tag type="info">{{grantForm.username}}</el-tag>
              </el-form-item>
              <el-form-item label="请选择角色:">
                <el-select v-model="roleId" placeholder="请选择角色">
                    <!-- 遍历请求回来的数据，动态渲染 -->
                  <el-option v-for = "(role, index) in roleNameList" :key = "index" :label="role.roleName" :value="role.id"></el-option>
                </el-select>
              </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
              <el-button @click="grantDialogFormVisible = false">取 消</el-button>
                <!-- 点击按钮提交分配角色 -->
              <el-button type="primary" @click="grantUserSubmit()">确 定</el-button>
            </div>
        </el-dialog>
    </div>
</template>
<script>
import {getUserList,changeUserState,addUser,getUser,editUser,deleteUser,getRoleList,grantUserRole} from '@/api/api.js'
export default {
     data() {
      return {
        loading: true,
        total: 0,  // 一共有多少条， 默认是0条
        query: '',  //  搜索用户名的默认值为空
        pagesize: 10, // 每页显示多少条, 默认是10条
        pagenum: 1,  // 当前是第几页， 默认是第一页
        userList: [], // 默认表格数据为空
        addDialogFormVisible: false,
        addForm: {
          username: '',
          password: '',
          email: '',
          mobile: '',
        },
        editDialogFormVisible: false,
        editForm: {
          username: '',
          email: '',
          mobile: '',
          id: 0
        },
        grantDialogFormVisible: false,
        grantForm: {},
        roleNameList: [], 
        roleId: '',
        //   rules属性添加用户表单的校验规则 
        rules: {
            username: [
              { required: true, message: '请输入用户名', trigger: 'blur' }
            ],
            password: [
              { required: true, message: '请输入密码', trigger: 'blur' }
            ],
            email: [
              { required: true, message: '请输入邮箱地址', trigger: 'blur' },
              { type: "email", message: '请输入正确的邮箱地址', trigger: 'blur,change' }
            ],
            password: [
              { required: true, message: '请输入电话号码', trigger: 'blur' }
            ]
        }
      }  
    },
    created() {
        this.initList()  //  渲染数据到表格中
    },
    methods: {
      handleSizeChange(val) {
        // console.log(`每页 ${val} 条`)
        //  当每页多少条的值改变的时候，发送请求，渲染表格数据
        this.pagesize = val
        this.initList()
      },
      handleCurrentChange(val) {
        // console.log(`当前页: ${val}`)
        //  当当前页的值改变的时候，发送请求，渲染表格数据
        this.pagenum = val
        this.initList()
      },
      // 发送请求， 初始化渲染表格数据
      initList() {
          //  发送请求前， 显示加载
          this.loading = true
           // 发送请求需要传的参数
          getUserList({params: {query: this.query, pagenum: this.pagenum, pagesize: this.pagesize}}).then(res => {
              // 发送请求获取到的所有数据
            //   console.log(res)
              // 通过发送请求，获取用户列表数据
              this.userList = res.data.users
              //  通过发送请求，获取一共有多少条
              this.total = res.data.total
              //  请求完毕后，取消加载
              this.loading = false
          })
      },
    //   更改用户状态
      changeUserState(row) {
        //   console.log(row)
          changeUserState({uid: row.id, type: row.mg_state}).then(res => {
            //   console.log(res)
              // 判断是否更改用户状态成功
              if(res.meta.status === 200) {
                   this.$message({
                      type: 'success',
                      message: '设置用户状态成功'
                   });
              }else{
                   this.$message({
                      type: 'warning',
                      message: 'res.meta.msg'
                   });
              }
          })
      },
    //   添加用户
      addUserSubmit(formName) {
          this.$refs[formName].validate(valide => {
              if(valide) {
                 // 执行添加用户方法
                 addUser(this.addForm).then(res => {
                    //  console.log(res)
                     if(res.meta.status === 201) {
                         this.$message({
                            type: 'success',
                            message: '添加用户成功'
                         })
                     }else{
                         this.$message({
                            type: 'warning',
                            message: 'res.meta.msg'
                         });
                     }
                     this.addDialogFormVisible = false
                     // 添加成功后，重新刷新数据
                     this.initList()
                 })
              }
          })
      },
       //   显示编辑用户对话框
      showEditDialogFormVisible(row) {
          console.log(row)
          this.editDialogFormVisible = true // 点击编辑按钮，显示编辑用户对话框
          getUser(row.id).then(res => {
              console.log(res)
              // 判断是否获取到数据，如果获取到数据，就将数据渲染
              if(res.meta.status === 200) {
                  this.editForm.username = res.data.username
                  this.editForm.email = res.data.email
                  this.editForm.mobile = res.data.mobile
                  this.editForm.id = res.data.id
              }
          })
      },
        //  编辑用户信息提交
      editUserSubmit(formName) {
           this.$refs[formName].validate(valide => {
               if(valide) {
                   editUser(this.editForm).then(res => {
                       console.log(res)
                       if(res.meta.status === 200) {
                           this.$message({
                               type: 'success',
                               message: '编辑用户信息成功'
                           })
                       }else{
                           this.$message({
                            type: 'warning',
                            message: 'res.meta.msg'
                         });
                       }
                    this.editDialogFormVisible = false
                    this.initList()
                   }) 
               }
           })
      },
      //  删除用户信息
      showDeleteDialogFormVisible(row) {
           this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
           }).then(() => {
             // 执行删除用户操作，发送请求
             deleteUser(row.id).then(res => {
                 console.log(res)
                 if(res.meta.status === 200) {
                      this.$message({ 
                        type: 'success',
                        message: '删除成功!'
                      })
                    this.initList()
                 }
             }) 
             }).catch(() => {this.$message({
                                type: 'info',
                                message: '已取消删除'
                             })      
                })
      },
      // 显示分配角色对会话框
      showgrantDialogFormVisible(row) {
          this.grantDialogFormVisible = true
        //   console.log(row,9999)
          this.grantForm = row
          getRoleList().then(res => {
            //   console.log(res,8888)
              if(res.meta.status === 200) {
                 this.roleNameList = res.data
              }else{
                this.$message({
                    type: 'warning',
                    message: 'res.meta.msg' 
                })
              }
          })
      },
      //  分配角色提交
      grantUserSubmit() {
         if(!this.roleId){
             this.$message({
                 type: 'error',
                 message: '角色不能为空,请选择'
             })
         }else{
              grantUserRole({id: this.grantForm.id, rid: this.roleId}).then(res => {
                    console.log(res)
                    if(res.meta.status === 200) {
                      this.$message({ 
                              type: 'success',
                              message: '设置角色成功!'
                      })
                    }else{
                      this.$message({
                          type: 'warning',
                          message: 'res.meta.msg' 
                      })
                    }
                 this.grantDialogFormVisible = false
              })
         }
      }
    }
   
};
</script>
<style lang="scss" scoped>
.user {
  .margin20{
      margin: 20px 0;
  }
  .search-input {
    width: 300px;
  }
  .page{
      padding: 5px 0;
      background-color: #D3DCE6
  }
}
</style>



